import { PropType, computed, defineComponent, provide, ref, watch } from 'vue';
import Item from './Item';

export interface AccordionProps {
    multi?: boolean,
    activeKey?: any,
    flex?: boolean
}

const Accordion = defineComponent({
    name: 'Accordion',
    props: {
        multi: { type: Boolean as PropType<AccordionProps['multi']> },
        activeKey: { type: [String, Number, Array] as PropType<AccordionProps['activeKey']> },
        flex: { type: Boolean as PropType<AccordionProps['flex']>}
    },
    emits: ['select'],
    setup (props, {emit, slots}) {
        const classList = computed(() => ({
            'cm-accordion': true,
            'cm-flex-accordion': props.flex
        }));

        const activeKey = ref(props.activeKey ?? props.multi ? [] : '');

        watch(() => props.activeKey, (newVal) =>{
            activeKey.value = newVal;
        });

        const onSelect = (name, open, v) => {
            emit('select', name, open, v);
        };

        const ctx = {flex: props.flex, multi: props.multi, activeKey, onSelect: onSelect};
        provide('CMAccordionContext', ctx);

        return () => <div class={classList.value}>{slots.default?.()}</div>;
    },
});

Accordion.Item = Item;

export default Accordion;
